using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using F8Framework.Launcher;
using System.Linq;
using F8Framework.Core;

public class GameViewModel : INotifyPropertyChanged
{
    public ObservableCollection<MahjongTile> ChessBoardList { get; } = new();
    public ObservableCollection<MahjongTile> HandList { get; } = new();

    // --- 新增：命中规则名称 ---
    private string _matchedRuleName;
    public string MatchedRuleName
    {
        get => _matchedRuleName;
        set
        {
            if (_matchedRuleName != value)
            {
                _matchedRuleName = value;
                OnPropertyChanged();
            }
        }
    }

    // --- 新增：命中得分 ---
    private int _matchedScore;
    public int MatchedScore
    {
        get => _matchedScore;
        set
        {
            if (_matchedScore != value)
            {
                _matchedScore = value;
                OnPropertyChanged();
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged([CallerMemberName] string name = null)
        => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    
    /// <summary>
    /// 强制触发 PropertyChanged 事件（即使值相同）
    /// </summary>
    protected void ForcePropertyChanged([CallerMemberName] string name = null)
        => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));

    // --- 生成棋盘 ---
    public void GenerateTiles()
    {
        ChessBoardList.Clear();

        var tileData = FF8.Config.GetMahjong().Values.ToList();
        var random = new System.Random();
        var randomTiles = tileData.OrderBy(x => random.Next())
                                 .Take(ConstantModule.MAX_CHESS_BOARD_COUNT)
                                 .ToList();

        foreach (var tileConfig in randomTiles)
        {
            ChessBoardList.Add(new MahjongTile(tileConfig));
        }

        // 重置时强制触发 PropertyChanged（即使值相同，因为这是重置场景）
        MatchedRuleName = "";
        // 如果当前值已经是 0，直接强制触发事件；否则正常设置
        if (_matchedScore == 0)
        {
            ForcePropertyChanged(nameof(MatchedScore));
        }
        else
        {
            MatchedScore = 0;
        }
    }

    // --- 选择牌 ---
    public void PickTile(MahjongTile tile)
    {
        if (HandList.Count >= ConstantModule.MAX_HAND_COUNT)
            return;

        int index = ChessBoardList.IndexOf(tile);
        if (index < 0)
            return;

        ChessBoardList.RemoveAt(index);
        HandList.Add(tile);

        var tileData = FF8.Config.GetMahjong().Values.ToList();
        var random = new System.Random();
        if (tileData.Count > 0)
        {
            var newTileConfig = tileData[random.Next(tileData.Count)];
            var newTile = new MahjongTile(newTileConfig);
            ChessBoardList.Insert(index, newTile);
        }
    }

    // --- 出牌并检测规则 ---
    public void TrySendTile()
    {
        var matchedRule = RulesModule.EvaluateBestRule(HandList.ToList());

        if (matchedRule != null)
        {
            int score = matchedRule.ScoreBase + matchedRule.ScoreBonus;

            // 更新 MVVM 绑定属性
            MatchedRuleName = matchedRule.Name_CN;
            MatchedScore += score;
        }
        else
        {
            MatchedRuleName = "无匹配,扣除10分";
            MatchedScore -= 10;
            if (MatchedScore < 0)
            {
                MatchedScore = 0;
            }
        }

        // 清除手牌
        HandList.Clear();
    }
}
